/*
 * @Date: 2023-04-26 16:31:34
 * @Description:service统一出口
 * @LastEditors: hujingyang
 * @Author: hujingyang
 * @FilePath: \largeScreenDataVisualization\src\service\index.ts
 * @IDE: Created by VScode.
 */

import store from "@/store";
import { CLOSE_CONSOLE, getShopInfo, getSystemTime } from "./constant.apis";
import HJYRequest from "./request";
import { BASE_URL, TIMEOUT } from "./request/constant.config";
import type {
  HJYAxiosResponse,
  obtainDataType,
} from "./request/interface.types";
import router from "@/router";
import { ElNotification } from "element-plus";
import { formatTime, redirectUrl } from "@/common/utils";

/**网路请求类 */
const Request = new HJYRequest({
  baseURL: BASE_URL, //根url
  timeout: TIMEOUT, // 超时时间
  // 拦截器
  interceptors: {
    requestInterceptor: (config) => {
      config.headers.token = store.state?.token;
      config.headers.get["Content-Type"] =
        "application/x-www-form-urlencoded;charset=UTF-8";
      return config;
    },
    requestInterceptorCatch: (error) => {
      console.log("请求失败的拦截", error);
      ElNotification({
        title: "警告",
        message: "网络连接异常，请稍后重试",
        type: "warning",
      });
      return error;
    },
    responseInterceptor: (config: HJYAxiosResponse) => {
      const { data, config: requestConfig, request } = config;
      const token = requestConfig.headers?.token;
      const time = config?.headers?.date;

      if (!CLOSE_CONSOLE) {
        console.log(
          `%c${requestConfig.pageName}\nAPI地址:${
            requestConfig.url
          }\n调用API页面:${
            window.location.pathname
          }\n\ntoken:${token}\n响应时间:${
            time ? formatTime(new Date(time).getTime()) : time
          }\n`,
          "color: #ff00ea;",
          `
	        result.code==>【${data.code}】
	        result.success==>【${data.success}】
	        result.message==>【${data.message}】
	        result.data==>\n${data.data ? "" : JSON.stringify(data)}`,
          data.data
        );
      }

      //接口错误警告
      if (
        data.code !== 200 &&
        requestConfig.url !== getSystemTime[0] &&
        request.responseType !== "blob"
      ) {
        ElNotification({
          title: "通信错误",
          message: data.message ?? "当前服务通信中断，请稍后再试",
          type: "warning",
        });
      }

      return config;
    },
    responseInterceptorCatch: (error) => {
      console.log("响应失败的拦截", error);

      const { config, data, status } = error.response;
      const { url } = config;
      const { msg, code } = data;
      let message = "";

      switch (status) {
        case 401:
          message = msg ?? "您的登录已过期，请重新登录或联系管理员";
          redirectUrl(); //用户登录过期后，跳转至登录页面
          break;
        case 403:
          message = msg ?? "此接口已被禁用，请联系管理员";
          break;
        case 404:
          message = msg ?? "接口未找到，请联系管理员";
          break;
        default:
          message = msg ?? "系统错误，请联系管理员";
          break;
      }

      ElNotification({ title: "系统错误", message, type: "error" });

      if (url === getShopInfo[0]) {
        router.replace({ path: "/error", query: { code, message: msg } });
      }
      return error;
    },
  },
});

/**网络通信函数 */
export const obtainData = (config: obtainDataType): Promise<any> | void => {
  if (!CLOSE_CONSOLE) {
    console.groupCollapsed(
      `服务通信 => ${config.url[2]}（展开查看函数调用轨迹）`
    );
    console.log("该函数的调用轨迹如下");
    console.trace(); // 打印出该函数的调用轨迹
    console.groupEnd();
    config.pageName = config.url[2];
  }

  let url = config.url[0];

  //当使用url传参时，需要特殊处理入参
  if (config.data && url.includes("{") && url.includes("}")) {
    for (const key of Object.keys(config.data))
      url = url.replace(`{${key}}`, config.data[key]);
  }

  if (config.url[1].toLowerCase().trim() === "get" && config.data) {
    // config.params = config.data;
    // config.params = qs.stringify(config.data);
    url += "?"; // 拼接参数
    // 获取所有参数，通过循环 拼接所有参数，encodeURIComponent对参数编码，
    Object.keys(config.data).map((key) => {
      if (
        config.data &&
        config.data[key] !== undefined &&
        config.data[key] !== null
      ) {
        url += `${key}=${encodeURIComponent(config.data[key] ?? "")}&`;
      }
    });
    url = url.substring(0, url.length - 1); // 删除最后一个&字符
  }

  switch (config.url[1].toLowerCase().trim()) {
    case "get":
      return Request.get({ ...config, url });
    case "post":
      return Request.post({ ...config, url });
    case "delete":
      return Request.delete({ ...config, url });
    case "patch":
      return Request.patch({ ...config, url });
    default:
      alert("当前系统故障，请联系开发人员");
      break;
  }
};

/**
 *
 * import { obtainData } from "@/service";
 * import { getConfig } from "@/service/interfaceAddress";

async function request(showLoading: boolean) {
  const getData = await obtainData({
    url: getConfig,
    data: { a: "aa", b: { a: "1" }, c: [12] },
    showLoading,
    interceptors: {
      requestInterceptor: (config) => {
        console.log("单独请求的config", config);
        return config;
      },
      responseInterceptor: (config) => {
        console.log("单独响应的config");
        return config;
      },
    },
  });
  console.log("getData", getData);
}
 */

//获取上传文件路径
export const getUploadUrl = (API: string[]) => {
  return BASE_URL + API[0];
};
